package com.sxbbc.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.common.AgentMapping;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.CashVo;
import com.sxbbc.common.core.dto.jz.AgentInfoVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.AgentLevelEnums;
import com.sxbbc.common.core.enums.CashTypeEnums;
import com.sxbbc.common.core.enums.ParamEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.login.LoginTokenService;
import com.sxbbc.common.core.utils.BasePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zhangq
 * @since 2020/4/8
 */
@RestController
public class AgentController {
    @Autowired
    private IBankDetailService bankDetailService;
    @Autowired
    private ISysCashRuleService iSysCashRuleService;
    @Autowired
    private IBankDetailService iBankDetailService;
    @Autowired
    private ISysCashDetailsService iSysCashDetailsService;
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private IAddressService iAddressService;
    @Autowired
    private IAgAgentService iAgAgentService;
    @Autowired
    private IAgAccountService iAgAccountService;
    @Autowired
    private IAgMoneyDetailService iAgMoneyDetailService;

    @Autowired
    private IInfoParamService iInfoParamService;

    /**
     * 代理申请
     *
     * @param levelId
     * @param proId
     * @param cityId
     * @param areaId
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_APPLY)
    public RestResponse handleApply(Integer levelId, Integer proId, Integer cityId, Integer areaId, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        CCustomer customer = icCustomerService.getById(cid);
        if (calcuUtils.isEquals(customer.getAuthen(), StaticUtils.STATUS_NO)) {
            return GetRest.getFail("实名认证后,才能申请");
        }

        String addressExt = iAddressService.getAddrName(proId, cityId, areaId);
        if (addressExt.split(" ").length < 3) {
            return GetRest.getFail("请求参数有误，请重新提交");
        }

        QueryWrapper<AgAgent> wrapper = new QueryWrapper<>();
        wrapper.eq("cid", cid);
        wrapper.le("status", StaticUtils.STATUS_SUCCESS);
        int i = iAgAgentService.count(wrapper);
        if (i > 0) {
            return GetRest.getFail("您申请已受理，请勿重复提交");
        }

        QueryWrapper<AgAgent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("level", levelId).eq("status", StaticUtils.STATUS_SUCCESS);
        if (calcuUtils.isEquals(levelId, AgentLevelEnums.PROVINCE_AGENT.getId())) {
            queryWrapper.eq("pro_id", proId);
        } else if (calcuUtils.isEquals(levelId, AgentLevelEnums.CITY_AGENT.getId())) {
            queryWrapper.eq("pro_id", proId);
            queryWrapper.eq("city_id", cityId);
        } else if (calcuUtils.isEquals(levelId, AgentLevelEnums.AREA_AGENT.getId())) {
            queryWrapper.eq("pro_id", proId);
            queryWrapper.eq("city_id", cityId);
            queryWrapper.eq("area_id", areaId);
        }
        int count = iAgAgentService.count(queryWrapper);
        if (count > 0) {
            return GetRest.getFail("对不起,您选择的地区已有代理，请重新选择");
        }

        AgAgent agent = new AgAgent();
        agent.setCid(cid);
        agent.setLogin(customer.getLogin());
        agent.setPassWord(DESEncode.getInstance().encrypt(StaticUtils.DEFAULT_PASSWORD));
        agent.setPayWord(customer.getPayWord());
        agent.setName(customer.getNickName());
        agent.setStatus(StaticUtils.STATUS_APPLY);

        if (calcuUtils.isEquals(levelId, AgentLevelEnums.PROVINCE_AGENT.getId())) {
            agent.setProId(proId);
        } else if (calcuUtils.isEquals(levelId, AgentLevelEnums.CITY_AGENT.getId())) {
            agent.setProId(proId);
            agent.setCityId(cityId);
        } else if (calcuUtils.isEquals(levelId, AgentLevelEnums.AREA_AGENT.getId())) {
            agent.setProId(proId);
            agent.setCityId(cityId);
            agent.setAreaId(areaId);
        }
        agent.setLevel(levelId);
        agent.setAddressExt(addressExt);

        //判断是否是驳回后重新申请
        QueryWrapper<AgAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.eq("cid", cid).ge("status", StaticUtils.STATUS_FAIL);
        AgAgent agAgent = iAgAgentService.getOne(agentQueryWrapper);
        if (agAgent != null) {
            agAgent.setProId(proId);
            agAgent.setCityId(cityId);
            agAgent.setAreaId(areaId);
            agAgent.setLevel(levelId);
            agAgent.setStatus(StaticUtils.STATUS_APPLY);
            addressExt = iAddressService.getAddrName(proId, cityId, areaId);
            agAgent.setAddressExt(addressExt);
            iAgAgentService.updateById(agAgent);
        } else {
            iAgAgentService.save(agent);
        }
        return GetRest.getSuccess("申请成功，等待审核");
    }

    /**
     * 获取代理信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_GET_INFO)
    public RestResponse handleGetInfo(String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }

        QueryWrapper<AgAgent> agAgentQueryWrapper = new QueryWrapper<>();
        agAgentQueryWrapper.eq("cid", cid);
        AgAgent agAgent = iAgAgentService.getOne(agAgentQueryWrapper);
        if (!CalcuUtils.getInstance().isEquals(agAgent.getStatus(), StaticUtils.STATUS_SUCCESS)) {
            return GetRest.getFail("该代理还未通过审核");
        }
        QueryWrapper<AgAccount> agAccountQueryWrapper = new QueryWrapper<>();
        agAccountQueryWrapper.eq("cid", cid);
        AgAccount agAccount = iAgAccountService.getOne(agAccountQueryWrapper);

        //获取代理下的有效会员
        Integer value = CalcuUtils.getInstance().getValueByClass(int.class, iInfoParamService.getValueByCode(ParamEnums.EFFECTIVE_VALUE));
        agAgent.setEffectiveValue(value);
        int num = icCustomerService.selectEffectiveCustomerNum(agAgent);
        AgentInfoVo agentInfoVo = new AgentInfoVo();
        agentInfoVo.setMoney(agAccount.getMoney());
        agentInfoVo.setFreezeMoney(agAccount.getFreezeMoney());
        agentInfoVo.setNum(num);
        return GetRest.getSuccess("", agentInfoVo);
    }

    /**
     * 代理收益明细
     *
     * @param page
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_SELECT_MONEY_DETAILS)
    public RestResponse handleSelectMoneyDetails(BasePage<AgMoneyDetail> page, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        IPage<AgMoneyDetail> moneyDetails = iAgMoneyDetailService.handleSelectMoneyDetails(page, cid);
        return GetRest.getSuccess("", moneyDetails);
    }

    /**
     * 代理冻结明细
     *
     * @param page
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_SELECT_FREEZE_MONEY_DETAILS)
    public RestResponse handleSelectFreezeMoneyDetails(BasePage<AgFreezeMoneyDetail> page, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        IPage<AgFreezeMoneyDetail> agMoneyDetailIPage = iAgMoneyDetailService.handleSelectFreezeMoneyDetails(page, cid);
        return GetRest.getSuccess("", agMoneyDetailIPage);
    }

    /**
     * 代理提现明细
     *
     * @param page
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_SELECT_CASH_DETAILS)
    public RestResponse handleSelectCashDetails(BasePage<SysCashDetails> page, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        QueryWrapper<SysCashDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id", cid).eq("type", CashTypeEnums.AGENT.getId())
                .eq("status", StaticUtils.STATUS_SUCCESS).orderByDesc("end_time");
        IPage<SysCashDetails> sysCashDetailsIPage = iSysCashDetailsService.page(page, wrapper);
        return GetRest.getSuccess("", sysCashDetailsIPage);
    }

    /**
     * 代理提现申请前置数据
     *
     * @param token
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_SELECT_CASH_APPLY_INFO)
    public RestResponse handleSelectCashApplyInfo(String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        AgAgent agent = iAgAgentService.getOne(new QueryWrapper<AgAgent>().eq("cid", cid));

        CashVo cashVo = new CashVo();
        //查询余额
        AgAccount agAccount = iAgAccountService.selectByAgid(agent.getId());
        if (agAccount != null) {
            cashVo.setSummoney(agAccount.getMoney());
        }
        //查询银行卡
        BankDetail bank = new BankDetail();
        bank.setTargetId(agent.getId());

        List<BankDetail> bankList = iBankDetailService.queryBankDetailList(agent.getId(), CashTypeEnums.AGENT.getId());
        bankList.forEach(x -> x.setLastCode(x.getBankCard().substring(x.getBankCard().length() - 4, x.getBankCard().length())));
        CalcuUtils calcuUtils = new CalcuUtils();
        //查询提现规则
        QueryWrapper<SysCashRule> wrapper = new QueryWrapper<>();
        wrapper.eq("role_type", CashTypeEnums.AGENT.getId());
        SysCashRule sysCashRule = iSysCashRuleService.getOne(wrapper);
        cashVo.setBankList(bankList);
        cashVo.setRule(sysCashRule);
        cashVo.setScale(calcuUtils.mul(sysCashRule.getScale(), BigDecimal.valueOf(100), 2).stripTrailingZeros().toBigInteger());
        return GetRest.getSuccess("", cashVo);
    }

    /**
     * 代理提现申请
     *
     * @param token
     * @param cash
     * @return
     */
    @RequestMapping(value = AgentMapping.AG_HANDLE_CASH_APPLY)
    public RestResponse handleCashApply(String token, String payWord, SysCashDetails cash) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        cash.setTargetId(cid);
        return iAgAgentService.cashApply(cash, payWord);
    }

}
